package com.huadao.cart_ccs.common;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.widget.Toast;

import com.huadao.cart_ccs.main.CartApplication;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class FileUtils {

    //错误报告文件的扩展名
    public static final String CRASH_REPORTER_EXTENSION = ".cr";
    private static final Object obj = new Object();
    private static final Object obj_raw = new Object();

    private static FileUtils util = null;

    private static long fileSize=1024*1024;//日志文件默认大小

    private FileUtils() {
//        this.context = context;
    }

    public static FileUtils getInstance() {
        if (util == null) {
            util = new FileUtils();
        }
        return util;
    }

    public static void writeFile(File file, long maxFileSize,String msg, boolean appendLineReturn) throws IOException {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileWriter fw = null;
        if (file.exists()) {
            if (file.length() > maxFileSize) {
                fw = new FileWriter(file, false);
            } else {
                fw = new FileWriter(file, true);
            }
        } else {
            fw = new FileWriter(file, false);
        }

        fw.write(msg);
        if (appendLineReturn) {
            fw.write(13);
            fw.write(10);
        }
        fw.flush();
        fw.close();
    }

    public static String readFile(File file,long maxLength) throws IOException {
        if (!file.exists()) {
            return "";
        } else {
            long n = maxLength;
            long len = file.length();
            long skip = len - n;
            FileReader fr = new FileReader(file);
            fr.skip(Math.max(0, skip));
            char[] cs = new char[(int) Math.min(len, n)];
            fr.read(cs);
            return new String(cs).trim();
        }
    }

    //为了提高效率，不使用锁，不关闭流，但是为了线程安全，请使用单线程操作
    public static void writeRawMessageFile(String msg) {
//        synchronized (obj_raw) {
            try {
                File file = new File(Constants.logDir, Constants.RawMessagefileName);
                String dateStr = TimeUtil.log_sdf.format(new Date());
                String test = String.format("[%s] %s", dateStr, msg);
                writeFile(file,fileSize, test, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        }
    }

//    public static void readRawMessageFile(String msg) {
//            try {
//                File file = new File(Constants.logDir, Constants.RawMessagefileName);
//                String dateStr = TimeUtil.log_sdf.format(new Date());
//                String test11 = String.format("[%s] %s", dateStr, msg);
//                writeFile(file, test11, true,true);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//    }

    /**
     * 获得文件存储路径
     *
     * @return
     */
    public static String getFilePath(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//如果外部储存可用
            return context.getExternalFilesDir(null).getPath();//获得外部存储路径,默认路径为 /storage/emulated/0/Android/data/com.waka.workspace.logtofile/files/Logs/log_2016-03-14_16-15-09.log
        } else {
            return context.getFilesDir().getPath();//直接存在/data/data里，非root手机是看不到的
        }
    }

    /**
     * 对外接口  获取uri对应的路径
     *
     * @param uri
     * @return
     */
    public String getChooseFileResultPath(Context context, Uri uri) {
        String chooseFilePath = null;
        if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
            chooseFilePath = uri.getPath();
            Toast.makeText(context, chooseFilePath, Toast.LENGTH_SHORT).show();
            return chooseFilePath;
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
            chooseFilePath = getPath(context, uri);
        } else {//4.4以下下系统调用方法
            chooseFilePath = getRealPathFromURI(context, uri);
        }
        return chooseFilePath;
    }

    private String getRealPathFromURI(Context context, Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    private String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Toast.makeText(CartApplication.getInstance(), "type:" + type, Toast.LENGTH_SHORT).show();

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];

//                    final int splitIndex = docId.indexOf(':', 1);
//                    final String tag = docId.substring(0, splitIndex);
//                    final String path = docId.substring(splitIndex + 1);
//
//                    String nonPrimaryVolume = getPathToNonPrimaryVolume(context, tag);
//                    if (nonPrimaryVolume != null) {
//                        String result = nonPrimaryVolume + "/" + path;
//                        File file = new File(result);
//                        if (file.exists() && file.canRead()) {
//                            return result;
//                        }
//                    }
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);

            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);

            }

        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);

        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            uri.getPath();

        }
        return null;
    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    public static String getPathToNonPrimaryVolume(Context context, String tag) {
        File[] volumes = context.getExternalCacheDirs();
        if (volumes != null) {
            for (File volume : volumes) {
                if (volume != null) {
                    String path = volume.getAbsolutePath();
                    if (path != null) {
                        int index = path.indexOf(tag);
                        if (index != -1) {
                            return path.substring(0, index) + tag;
                        }
                    }

                }
            }
        }

        return null;
    }

//    /**
//     * 将crash信息写入文件中
//     *
//     * @param msg
//     */
//    public static String writeCrashToFile(String msg) {
//        Date date = new Date();
//        String fileName = Constants.CrashFilePath + "/log_" + TimeUtil.crash_log_sdf.format(date) + CRASH_REPORTER_EXTENSION;//log日志名，使用时间命名，保证不重复
//        String log = TimeUtil.crash_log_sdf.format(date) + msg + "\n";//log日志内容，可以自行定制
//
//        //如果父路径不存在
//        File file = new File(Constants.CrashFilePath);
//        if (!file.exists()) {
//            file.mkdirs();//创建父路径
//        }
//
//        FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法，不用关闭
//        BufferedWriter bw = null;
//        try {
//
//            fos = new FileOutputStream(fileName, true);//这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
//            bw = new BufferedWriter(new OutputStreamWriter(fos));
//            bw.write(log);
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (bw != null) {
//                    bw.close();//关闭缓冲流
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return fileName;
//    }
}
